import os
from datetime import datetime

from langchain_openai import ChatOpenAI
from ticket_state import TicketState
from dotenv import load_dotenv

load_dotenv()

# 初始化大模型（企业级推荐GPT-4o或Claude 3.5）
llm = ChatOpenAI(
    model= os.getenv("model"),
    api_key= os.getenv("dashscope_api_key"),
    base_url= os.getenv("dashscope_base_url"),
    temperature=0)

# 节点1：意图识别（AI推理节点）
def intent_recognition_node(state: TicketState) -> TicketState:
    """识别用户请求的意图，更新state.intent"""
    prompt = f"用户请求：{state.user_query}\n请判断意图（仅返回'售后'/'咨询'/'投诉'/'其他'）"
    intent = llm.invoke(prompt).content.strip()
    # 记录执行历史（审计用）
    state.history.append({
        "node": "intent_recognition",
        "result": intent,
        "timestamp": datetime.now().isoformat()
    })
    print(f"意图识别结果：{intent}")
    return state.model_copy(update={"intent": intent})

# 节点2：工单分类（基于意图的条件处理）
def category_node(state: TicketState) -> TicketState:
    """根据意图进一步分类工单，更新state.category"""
    if state.intent == "售后":
        category = "产品故障" if "坏了" in state.user_query else "退款申请"
    elif state.intent == "咨询":
        category = "功能咨询" if "怎么用" in state.user_query else "价格咨询"
    else:
        category = "其他"
    state.history.append({"node": "category", "result": category})
    return state.model_copy(update={"category": category})

# 节点3：分配处理人员（基于分类的路由）
def assign_node(state: TicketState) -> TicketState:
    """根据分类分配处理人员，更新state.assigned_to"""
    assignee_map = {
        "产品故障": "tech_support@example.com",
        "退款申请": "finance@example.com",
        "功能咨询": "product@example.com"
    }
    assigned_to = assignee_map.get(state.category, "admin@example.com")
    state.history.append({"node": "assign", "result": assigned_to})
    return state.model_copy(update={"assigned_to": assigned_to})

if __name__ == '__main__':
    print("===== 工单处理系统测试 =====")
    
    # 测试场景1：退款申请工单
    print("\n[测试场景1] 退款申请工单")
    ticket1 = TicketState(ticket_id="TICKET-001", user_query="我想退款，产品不太符合我的需求")
    print(f"初始状态: {ticket1.dict()}")
    
    # 执行意图识别
    ticket1 = intent_recognition_node(ticket1)
    print(f"意图识别后: intent={ticket1.intent}")
    
    # 执行分类
    ticket1 = category_node(ticket1)
    print(f"分类后: category={ticket1.category}")
    
    # 执行分配
    ticket1 = assign_node(ticket1)
    print(f"分配后: assigned_to={ticket1.assigned_to}")
    print(f"执行历史: {ticket1.history}")
    
    # 测试场景2：产品故障工单
    print("\n[测试场景2] 产品故障工单")
    ticket2 = TicketState(ticket_id="TICKET-002", user_query="我的设备坏了，无法开机")
    
    # 模拟意图为售后
    ticket2.intent = "售后"
    ticket2 = category_node(ticket2)
    ticket2 = assign_node(ticket2)
    print(f"工单ID: {ticket2.ticket_id}")
    print(f"分类: {ticket2.category}")
    print(f"分配给: {ticket2.assigned_to}")
    
    # 测试场景3：功能咨询工单
    print("\n[测试场景3] 功能咨询工单")
    ticket3 = TicketState(ticket_id="TICKET-003", user_query="请问这个功能怎么用？")
    
    # 模拟意图为咨询
    ticket3.intent = "咨询"
    ticket3 = category_node(ticket3)
    ticket3 = assign_node(ticket3)
    print(f"工单ID: {ticket3.ticket_id}")
    print(f"分类: {ticket3.category}")
    print(f"分配给: {ticket3.assigned_to}")
    
    # 测试场景4：价格咨询工单
    print("\n[测试场景4] 价格咨询工单")
    ticket4 = TicketState(ticket_id="TICKET-004", user_query="这个产品价格是多少？有优惠吗？")
    
    # 模拟意图为咨询
    ticket4.intent = "咨询"
    ticket4 = category_node(ticket4)
    ticket4 = assign_node(ticket4)
    print(f"工单ID: {ticket4.ticket_id}")
    print(f"分类: {ticket4.category}")
    print(f"分配给: {ticket4.assigned_to}")
    
    # 测试场景5：其他类型工单
    print("\n[测试场景5] 其他类型工单")
    ticket5 = TicketState(ticket_id="TICKET-005", user_query="我想提个建议")
    
    # 模拟意图为其他
    ticket5.intent = "其他"
    ticket5 = category_node(ticket5)
    ticket5 = assign_node(ticket5)
    print(f"工单ID: {ticket5.ticket_id}")
    print(f"分类: {ticket5.category}")
    print(f"分配给: {ticket5.assigned_to}")
    
    print("\n===== 测试完成 =====")
